$(function(){
    /* work_list 的 js */
    (function(){
        var msCategoryAll   = 'full_series';
        var slider;
        var currentWorkPage = 1;
        var category        = [];
        var workLoading     = false;
        var $grid;

        $(document).ready(function () {
            resizeWorks();
        });
        $(window).load(function () {
        });
        var timeout;
        $(window).scroll(function (e) {
            animated = false;
            clearTimeout(timeout);
            timeout = setTimeout(scrollMenu, 500);
        });
        $(window).resize(function (e) {
            resizeHeight();
            blankHeight();
            // resizeWorks();
        //    if ($(window).width() >= 992) {
        //        if ($('.hidden-mobile').is(':hidden')) {
        //            $('.hidden-mobile').show();
        //            $('.menu-btn').removeClass('active');
        //        }
        //    }
            //setImageCover($('.client img'));


        });
        $(window).bind('popstate', function (event) {

        });
        /*var s     = skrollr.init({
         forceHeight: false,
         mobileCheck: function () {
         //hack - forces mobile version to be off
         return false;
         }
         });*/
        function resizeWorks() {
            // var iScale        = 0.6;
            // var padding       = parseInt($('.work-item').css('padding-right'));
            // var workListWidth = $('.holder').width() + padding;
            // $('.works-wrap').width(workListWidth);
            // var height  = Math.floor($('.work-item-sizer').innerWidth() * iScale);
            // var height2 = Math.floor($('.work-item.width2').innerWidth() * iScale);
            // var height3 = Math.floor($('.work-item.width3').innerWidth() * iScale);
            // var height4 = Math.floor($('.work-item.width4').innerWidth() * iScale);
            // if (height % 2 != 0) {
            //     height++;
            // }
            // if (height2 % 2 != 0) {
            //     height2++;
            // }
            // if (height3 % 2 != 0) {
            //     height3++;
            // }
            // if (height4 % 2 != 0) {
            //     height4++;
            // }

            // if ($(window).width() <= 480) {
            //     $('.work-item').height(height);
            // } else {
            //     $('.work-item').height(height);
            //     $('.work-item.width2').height(height2 + padding);
            //     $('.work-item.width3').height(height3 + padding + padding);
            //     $('.work-item.width4').height(height4 + padding);
            // }
            //$('.works-wrap').packery('shiftLayout');
            $('.works-wrap').packery();
            // setImageCover($('.work-item .content img'));
        }

        function blankHeight() {
        //    $('.blank').height($('footer').height());
        }

        function scrollMenu() {
            if ($('#popup-slider').hasClass('active')) {
                history.replaceState(null, null, ($('.filter-btn.selected').attr('href') == '' ? getPath() + 'works/' + msCategoryAll : $('.filter-btn.selected').attr('href')) + (currentWorkPage > 1 ? '?page=' + currentWorkPage : ''));
                changeTitle('Works');
            }
        }

        function loadPage() {
            var loc      = history.location || document.location;
            var locStr   = loc.toString();
            var locQuery = locStr.replace(gsPath, '');
            var locQuery = locQuery.replace(sLangS + '/', '');
            var locArr   = locQuery.split('/');
            if (locArr[locArr.length - 1].indexOf('?') >= 0) {
                locArr[locArr.length - 1] = locArr[locArr.length - 1].substring(0, locArr[locArr.length - 1].indexOf('?'));
            }
            //console.log(locArr);

            if (locArr[0] != undefined) {
                if (locArr[0] == 'about' || locArr[0] == 'services') {
                    var tempObj = {
                        about:    'about',
                        services: 'services'
                    }
                    showPopup($('#' + tempObj[locArr[0]]).html());
                    $('#popup-slider').attr('data-tag', tempObj[locArr[0]]);
                    $('.menu-' + tempObj[locArr[0]]).parent().toggleClass('selected');
                    return;
                }
                if (locArr[0] == 'contact') {
                    $('.menu-contact').trigger('click');
                    return;
                }
                if (locArr[0] == 'works' && locArr[1] != undefined && locArr[1] != '') {
        //            if (locArr[1] == msCategoryAll || locArr[1] == 'company' || locArr[1] == 'event' || locArr[1] == 'shopping_cart' || locArr[1] == 'reference') {
                    if (locArr[1] == msCategoryAll || $.inArray(locArr[1], category) >= 0) {
                        if (getQueryParameter('page') != null) {
                            page = getQueryParameter('page');
                            if ($.isNumeric(page)) {
                                page = parseInt(page);
                            } else {
                                page = 1;
                            }
                            currentWorkPage = 1;

                            if (locArr[1] != msCategoryAll) {
                                $('.filter-btn').removeClass('selected');
                                $('.filter-btn[href="' + locArr[1] + '"]').addClass('selected');
                            }

                            $('.work-item').remove();
                            settings     = {
                                data:      {
                                    //sW: [
                                    //    {
                                    //        sF: 'bRecommend',
                                    //        sV: 0
                                    //    }
                                    //]
                                },
                                iP:        currentWorkPage,
                                sCategory: (locArr[1] == msCategoryAll) ? '' : locArr[1]
                            };
                            var callback = function () {
                                if (currentWorkPage < page) {
                                    currentWorkPage++;
                                    settings['iP'] = currentWorkPage;
                                }
                            };
                            $('html, body').animate({
                                scrollTop: $('#part4-area').offset().top - $('header').height()
                            }, 1000, function () {

                            });
                            return;
                        } else if (locArr[1] != msCategoryAll) {
                            filterWork(locArr[1]);
                        }
                        $('html, body').animate({
                            scrollTop: $('#part4-area').offset().top - $('header').height()
                        }, 1000, function () {

                        });
                        return;
                    } else if ($('[data-title=' + locArr[1] + ']').length > 0) {
                        var obj = $('[data-title=' + locArr[1] + ']');
                        $('html, body').animate({
                            scrollTop: $('#part4-area').offset().top - $('header').height()
                        }, 1000, function () {
                            showPopup($(obj).data('data'));
                        });
                        return;
                    } else {
                        return;
                    }
                }
                $('[data-title]').each(function (i, e) {
                    if ($(e).attr('data-title') == locArr[0]) {
                        $('html, body').animate({
                            scrollTop: $(e).offset().top - $('header').height()
                        }, 1000);
                    }
                });
            }
        }

        function resizeHeight() {
            var height = $(window).height();
            if ($(window).height() <= 992) {
                height = height - $('header').height();
            }
        }

        function setWorkData(obj) {
            //console.log(obj);

            var slide = [];
            if (obj['images'] != null) {
                $.each(obj['images'], function (x, z) {
                    slide.push(z['sImage']);
                });
            } else {
                slide = false;
            }
            var data = {
                id:        obj['iProductID'],
                key:       obj['sProductKey'],
                width:     (obj["iValue01"] == 1) ? '' : 'width' + obj["iValue01"],
                cat:       Object.keys(obj['categories']),
                title:     getStrReplaceCode(obj[sLang]["sName"]),
                name:      obj[sLang]["sName"],
                content:   obj[sLang]["sDesc"],
                link:      obj[sLang]["sInfoValue03"],
                icon:      obj["sIcon"],
                slide:     slide,
                challenge: obj[sLang]["sInfoValue04"],
                solution:  obj[sLang]["sInfoValue05"],
                service:   obj[sLang]["sInfoValue06"]
            };
            return data;
        }

        function filterWork(category) {
            currentWorkPage = 1;
            $('html, body').animate({
                scrollTop: $('#part4-area').offset().top - $('header').height()
            }, 1000);
            $('.work-item').remove();

            var sLink = getPath() + 'works/' + category;
            history.replaceState(null, null, sLink);

        //    resizeWorks();
            $('.filter-btn').removeClass('selected');
            $('[data-key=' + category + ']').addClass('selected');
            $('#more-work').css({
                display: 'initial'
            });
        //    if (category == msCategoryAll) {
        ////        $('.work-item').fadeIn(200, function () {
        ////            setImageCover($('.work-item .content img'));
        ////            $grid.packery();
        ////        });window.location.href
        //
        //        getProduct({data: {sW: [{sF: 'bRecommend', sV: 0}]}});
        //    } else {
        //        getProduct({data: {sW: [{sF: 'bRecommend', sV: 0}]}, sCategory: category});
        //    }
        //    resizeWorks();
        }

        $(function () {
            animated = false;
            $('.menu li a[scrollto], .menu li a[data-tag], .menu li a.menu-contact').click(function (e) {
                e.preventDefault();
            });

            $('.filter-wrap').delegate('.filter-btn', 'click', function (e) {
                e.preventDefault();
        //        $('.filter-btn').removeClass('selected');
        //        $(this).addClass('selected');
                filterWork($(this).attr('data-key'));
            });
            var isLoading = false;
            var imgArr    = [];
            $('.works-wrap').delegate('.work-item', 'click', function () {
        //        if (!isLoading) {
        //            isLoading = true;
                var data = $(this).data('data');
        //            var slide = $(this).data('data')['slide'];
        //            $('body').on('image-loaded', function () {
        //                if (imgArr.length == slide.length) {
                if ($('#popup-slider').hasClass('active')) {
                    showPopup(data);
                    $('#popup-slider').attr('data-tag', 'work');
                }
        //                    $('body').off('image-loaded');
        //                    isLoading = false;
        //                    imgArr = [];
        //                }
        //            });
        //            if (slide.length > 0) {
        //                $.each(slide, function (i, e) {
        //                    var o = new Image;
        //                    o.src = e, $(o).load(function () {
        //                        imgArr.push(true);
        //                        $('body').trigger("image-loaded");
        //                    });
        //                });
        //            }
        //        } else {
        //            imgArr = [];
        //        }
            });
            $('.works-wrap').delegate('.work-link', 'click', function (e) {
                e.preventDefault();
            });
            $('.load_more').click(function (e) {
                e.preventDefault();

            });
            $('#popup-slider').delegate('.slider-left', 'click', function () {
                $(slider).trigger('prev.owl.carousel');
            });
            $('#popup-slider').delegate('.slider-right', 'click', function () {
                $(slider).trigger('next.owl.carousel');
            });
        });



        var BACK_SHOW_HEIGHT = 120;//滚动多少返回顶部显示
        var GOLBAL_TIMER = null;
        var GOLBAL_TIMROUT = null;

        //图片加载
        (function () {
          var imgLength = $('img').length;
          var count = 0;
          $('img').each(function (index, item) {
            imgLoad(item, function () {
              count++;
              var progress = Math.round(count / imgLength) * 100;
              if (progress >= 100) {
                $('.global_progress').fadeOut();
                progress = 100;
              }
              $('.global_progress').find('span').html('' + progress + '%');
              $('.progress_strip').animate({width: progress + '%'}, 10)
            })
          });

          function imgLoad(img, callback) {
            var timer = setInterval(function () {
              if (img.complete) {
                callback(img);
                clearInterval(timer)
              }
            }, 50)
          };
        })();

        $(function () {
          try {
            var $grid = $('.works-wrap').packery({
              itemSelector:    '.work-item',
              columnWidth:     '.grid-sizer',
              gutter:          0,
              // gutter: '.gutter-sizer',
              percentPosition: true,
              // isInitLayout:  false,
              // isResizeBound: false
            });
          } catch (e){

          }

        //works 点击加载更多
        $('.load_more').click(function (e) {
              //发送ajax获取的数据
              try {
                var mockData = {
                  code: 0,
                  mes: '成功',
                  result: {
                    works: [
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works91'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: true,
                        title: 'works25'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works2'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works9'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: true,
                        title: 'works5'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works3'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works2'
                      },
                      {
                        img: './../img/work2.jpg',
                        isBig: false,
                        title: 'works1'
                      }
                    ]
                  }
                };

                var compiled = _.template($('#work-template').html());
                $.each(mockData.result.works, function (index, item) {
                  var $item = $(compiled(item));

                  $grid.append($item).packery('appended', $item);
                });
                e.preventDefault();
                return false;
              } catch(err) {

              }
            });
        });
    })()

    /* 除了主页其他页面都共有的js */        
})